<template>
  <Transition name="slide-fade">
    <van-button class="back-top-btn" round type="primary" icon="back-top" v-show="isShow" @click="backTo"></van-button>
  </Transition>
</template>

<script setup>
import { ref, onMounted } from 'vue';

const isShow = ref(false)

let windowTopLocation = 0

const listener = () => {
  windowTopLocation = document.documentElement.scrollTop
  if (windowTopLocation >= 600) {
    isShow.value = true
  } else {
    isShow.value = false
  }
}
// 获取当前滚动高度
onMounted(() => {
  window.addEventListener('scroll', listener, true)
})
// 点击后返回顶部
const backTo = () => {
  let AnSerter = setInterval(() => {
    document.documentElement.scrollTop = windowTopLocation
    windowTopLocation -= ((windowTopLocation / 30) + 3)
    if (windowTopLocation <= -20) {
      clearInterval(AnSerter)
    }
  }, 1)
}

</script>

<style scoped>
.back-top-btn {
  width: 35px;
  height: 35px;
  background-color: #323233;
  opacity: 0.8;
  border: none;
  position: fixed;
  right: 2.4vw;
  bottom: 10vh;
  z-index: 999;
}

.slide-fade-enter-active {
  transition: all 0.3s ease-out;
}

.slide-fade-leave-active {
  transition: all 0.3s ease-in;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  transform: translateX(20px);
  opacity: 0;
}
</style>
